package com.auto.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws Exception {
        //创建ServerSocketChannel --> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //创建一个Selector
        Selector selector = Selector.open();

        //绑定端口6666，省略绑定主机名，在服务端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        //把serverSocketChannel注册到selector中，并 关心 事件为OP_ACCEPT连接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等待客户端连接
        while (true) {
            //等待1秒，如果没有事件发生，返回
            if (selector.select(1000) == 0) {
                System.out.println("等待了1秒，无连接");
                continue;
            }

            //有连接，就获取关注的事件，从而反向获取channel
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey selectionKey = keyIterator.next();
                //判断是否为事件OP_ACCEPT连接事件
                if (selectionKey.isAcceptable()) {//有连接事件
                    //创建SocketChannel --> Socket
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功："+socketChannel.hashCode());
                    //将SocketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将SocketChannel注册到selector中，关注事件OP_READ，读事件
                    //给socketChannel关联一个ByteBuffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                //判断事件是否为OP_READ，读事件
                if (selectionKey.isReadable()) {
                    //根据selectionKey反向获取SocketChannel --> Socket
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    //根据selectionKey获取对应的ByteBuffer
                    ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                    //将通道中的数据读取到缓冲区中
                    channel.read(buffer);
                    System.out.println("来自客户端：" + new String(buffer.array()));
                }
                //手动删除selectionKey，以防止重复操作0
                keyIterator.remove();
            }
        }
    }
}
